package cn.song.service.impl;

import cn.song.domain.ProductInfo;
import cn.song.dto.CardDto;
import cn.song.enums.ProductStatus;
import cn.song.enums.ResultEnum;
import cn.song.exceptions.SellException;
import cn.song.repository.ProductInfoRepository;
import cn.song.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Resource
    private ProductInfoRepository repository;


    @Override
    public ProductInfo save(ProductInfo pro) {
        return repository.save(pro);
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return  repository.findAll(pageable);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return repository.findByProductStatus(ProductStatus.UP.getCode());
    }

    @Override
    public ProductInfo findById(String id) {
        return repository.findOne(id);
    }

    @Override
    @Transactional
    public void increaseStock(List<CardDto> cartDTOList) {
        for (CardDto cardDto : cartDTOList){
            ProductInfo pr = repository.findOne(cardDto.getProductId());
            if(pr==null){
                new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer result = pr.getProductStock() + cardDto.getProductQuantity();
            pr.setProductStock(result);
            repository.save(pr);
        }

    }

    @Override
    public void decreaseStock(List<CardDto> cartDTOList) {
        for (CardDto cardDto : cartDTOList){
            ProductInfo pr = repository.findOne(cardDto.getProductId());
            if(pr==null){
               throw  new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            if((pr.getProductStock()-cardDto.getProductQuantity())<0){
                logger.error("******** shumu bugou");
                throw new SellException(ResultEnum.PRODUCT_NOT_ENOUGH);
            }
       Integer result = pr.getProductStock()-cardDto.getProductQuantity();
            pr.setProductStock(result);
            repository.save(pr);
        }

    }
}
